package command

import (
	"pan/api"
	"pan/common/conf"
	"pan/common/exception"
	"pan/common/log"

	"github.com/jedib0t/go-pretty/v6/progress"
)

type UploadCommand struct {
	dir       string
	filePath  string
	multipart bool

	// callback  *api.DownloadCallback
	pgWriter  progress.Writer
	pgTracker *progress.Tracker
}

func (u *UploadCommand) Run(opts []*Option, args []string) {
	if !u.parseOption(opts) {
		return
	}

	if !conf.IsTokenValid() {
		panic("token is invalid, you must login first")
	}

	req := &api.SingleUploadRequest{
		Dir:      u.dir,
		FilePath: u.filePath,
	}

	_, err := api.SingleUploadApi(conf.GlobalToken.Tokenid, req)
	if err != nil {
		panic(err)
	}
}

func (u *UploadCommand) singleUpload() error {
	req := &api.SingleUploadRequest{
		Dir:      u.dir,
		FilePath: u.filePath,
	}
	_, err := api.SingleUploadApi(conf.GlobalToken.Tokenid, req)
	return err
}

func (u *UploadCommand) multipartUpload() error {
	return exception.NewExpectError("not yet implemented")
}

func (u *UploadCommand) parseOption(opts []*Option) bool {
	for _, opt := range opts {
		switch opt.Name {
		case "dir":
			u.dir = opt.StrValue
		case "file":
			u.filePath = opt.StrValue
		case "multipart":
			u.multipart = opt.BoolValue
		}
	}
	if u.dir == "" {
		log.Error("doc dir is invalid")
		return false
	}
	if u.filePath == "" {
		log.Error("file is invalid")
		return false
	}
	return true
}

func (u *UploadCommand) Arguments() []Argument {
	return nil
}

func (u *UploadCommand) Options() []*Option {
	return []*Option{
		{
			ShortName:    "d",
			Name:         "dir",
			Description:  "doc dir in remote",
			OptType:      StrOption,
			DefaultValue: "",
		},
		{
			ShortName:    "f",
			Name:         "file",
			Description:  "file to upload",
			OptType:      StrOption,
			DefaultValue: "",
		},
		{
			ShortName:    "m",
			Name:         "multipart",
			Description:  "use multipart files, use single file to upload as default",
			OptType:      BoolOption,
			DefaultValue: false,
		},
	}
}

func (u *UploadCommand) Description() string {
	return "Download doc to local dir"
}

func NewUploadCommand() *UploadCommand {
	return &UploadCommand{}
}
